package com.example.administrator.printoutindemo;

import android.annotation.SuppressLint;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.jess.arms.utils.ArmsUtils;
import com.xiaoxing.gifloadingview.LoadingDialogUtil;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

import java.util.ArrayList;
import java.util.List;

import me.jessyan.armscomponent.commonres.utils.ToolbarUtils;
import com.jess.arms.base.BaseConstants;


public class StoreSGJLEditMaterialNums extends AppCompatActivity {

    private static final String WEBSERVICE_CONFIG = "TEXT";
    private static final int LOGINSUCCESS = 0;
    private static final int NETWORKERROR = 2;
    private static final int SYSERROR = 3;
    private static final int UPSUCCESS = 1;
    private static final int EMPTYERROR = 4;
    private static final int NO_DATA = 5;
    private AutoCompleteTextView s_qrc_fmmaterial = null;
    private TextView s_qrc_materialinfo = null;
    private TextView s_qrc_projectname = null;
    private EditText s_qrc_materialnums = null;
    private Button s_qrc_btn_search = null;
    private EditText s_qrc_fmmaterialnums = null;
    private Button s_qrc_btn_editnums = null;
    private List<FmMaterialDetailInfo> li_fm = null;
    private FmMaterialDetailInfo fmMaterialDetailInfo = null;
    private MyAutoAarryAdapter projectAda = null;
    private String SYSException = "";
    @SuppressLint("HandlerLeak")
    private final Handler hanlder = new Handler() {
        public void handleMessage(android.os.Message msg) {

            switch (msg.what) {
                case LOGINSUCCESS:
                    bindInfo();

                    LoadingDialogUtil.dismissDialog();
                    break;

                case UPSUCCESS:
                    bindInfo();
                    Toast.makeText(StoreSGJLEditMaterialNums.this, "修改数量成功!",
                            Toast.LENGTH_LONG).show();
                    LoadingDialogUtil.dismissDialog();
                    finish();

                    break;

                case NETWORKERROR:

                    Toast.makeText(StoreSGJLEditMaterialNums.this, "网络或系统异常!",
                            Toast.LENGTH_LONG).show();
                    LoadingDialogUtil.dismissDialog();

                    break;
                case SYSERROR:

                    Toast.makeText(StoreSGJLEditMaterialNums.this,
                            "系统异常!" + SYSException, Toast.LENGTH_LONG).show();
                    LoadingDialogUtil.dismissDialog();

                    break;
                case EMPTYERROR:

                    Toast.makeText(StoreSGJLEditMaterialNums.this, "请填写子物料数量!",
                            Toast.LENGTH_LONG).show();
                    LoadingDialogUtil.dismissDialog();

                    break;

                default:
                    LoadingDialogUtil.dismissDialog();

                    break;
            }

        }
    };
    private String out_storage_detail_Id = "";
    private SharedPreferences sPreferencces;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.store_activity_sgjleditmaterialnums);
        ToolbarUtils.initToolbarTitleBack(this, "物料数量修改");
        sPreferencces = getSharedPreferences(WEBSERVICE_CONFIG, 0);

        s_qrc_fmmaterial = (AutoCompleteTextView) findViewById(R.id.s_qrc_fmmaterial);// 子物料描述
        s_qrc_materialinfo = (TextView) findViewById(R.id.s_qrc_materialinfo);// 物料描述
        s_qrc_materialnums = (EditText) findViewById(R.id.s_qrc_materialnums);// 物料数量
        s_qrc_btn_search = (Button) findViewById(R.id.s_qrc_btn_search);// 搜索
        s_qrc_fmmaterialnums = (EditText) findViewById(R.id.s_qrc_fmmaterialnums);// 子物料数量
        s_qrc_btn_editnums = (Button) findViewById(R.id.s_qrc_btn_editnums);// 提交
        s_qrc_projectname = (TextView) findViewById(R.id.s_qrc_projectname);// 项目名称

        fmMaterialDetailInfo = new FmMaterialDetailInfo(this);

        // 接收
        OutStorageDetail odm = (OutStorageDetail) this.getIntent()
                .getSerializableExtra("OutStorageDetail");

        if (null != odm) {
            out_storage_detail_Id = odm.get_out_storage_detail_Id();

            s_qrc_materialinfo.setText(odm.get_material());
            s_qrc_materialnums.setText(odm.get_nums());
            s_qrc_projectname.setText(odm.get_projectname());

            //搜索
            s_qrc_btn_search.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    String s_qrc_fmmaterialTextValue = s_qrc_fmmaterial.getText().toString().trim();
                    if (!TextUtils.isEmpty(s_qrc_fmmaterialTextValue) && s_qrc_fmmaterialTextValue.contains("_")) {
                        String[] fminfo = s_qrc_fmmaterialTextValue.split("_");

                        if (fminfo.length > 0) {
                            String fmmid = fminfo[1];

                            for (FmMaterialDetailInfo f : li_fm) {

                                if (f.getFmmid().equals(fmmid)) {
                                    s_qrc_fmmaterialnums.setText(f.getNums());
                                }
                            }
                        }
                    } else {
                        ArmsUtils.makeText(StoreSGJLEditMaterialNums.this, "子物料描述为空");
                    }

                }
            });
            //提交
            s_qrc_btn_editnums.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    LoadingDialogUtil.showGifdialog2(getSupportFragmentManager(), R.drawable.public_loading);
                    new Thread(new Runnable() {

                        @Override
                        public void run() {

                            try {

                                String nums = s_qrc_materialnums.getText().toString();
                                String fmnums = s_qrc_fmmaterialnums.getText().toString();
                                String fmmid = "";

                                if (fmnums.equals("")) {
                                    Message m = new Message();
                                    m.what = StoreSGJLEditMaterialNums.EMPTYERROR;
                                    hanlder.sendMessage(m);
                                } else {
                                    String s_qrc_fmmaterialTextValue = s_qrc_fmmaterial.getText().toString().trim();
                                    boolean isContain = s_qrc_fmmaterialTextValue.contains("_");
                                    if (!TextUtils.isEmpty(s_qrc_fmmaterialTextValue) && isContain) {

                                        String[] fminfo = s_qrc_fmmaterialTextValue.split("_");

                                        if (fminfo.length > 0) {
                                            fmmid = fminfo[1];
                                        }

                                        boolean re = callWebServiceUpdateNums(nums, out_storage_detail_Id, fmnums, fmmid);

                                        if (re) {

                                            li_fm = callWebServiceGetFmInfo(out_storage_detail_Id);

                                            Message m = new Message();
                                            m.what = StoreSGJLEditMaterialNums.UPSUCCESS;
                                            hanlder.sendMessage(m);
                                        }
                                    } else {
                                        ArmsUtils.makeText(StoreSGJLEditMaterialNums.this, "请选择子物料");
                                    }
                                }


                            } catch (Exception e) {
                                Message m = new Message();
                                m.what = StoreSGJLEditMaterialNums.SYSERROR;
                                hanlder.sendMessage(m);
                            }

                        }
                    }).start();

                }
            });

            LoadingDialogUtil.showGifdialog2(getSupportFragmentManager(), R.drawable.public_loading);
            new Thread(new Runnable() {

                @Override
                public void run() {

                    try {

                        li_fm = callWebServiceGetFmInfo(out_storage_detail_Id);

                        if (li_fm != null) {
                            Message m = new Message();
                            m.what = StoreSGJLEditMaterialNums.LOGINSUCCESS;
                            hanlder.sendMessage(m);
                        } else {
                            Message m = new Message();
                            m.what = StoreSGJLEditMaterialNums.NO_DATA;
                            hanlder.sendMessage(m);
                        }

                    } catch (Exception e) {
                        Message m = new Message();
                        m.what = StoreSGJLEditMaterialNums.SYSERROR;
                        hanlder.sendMessage(m);
                    }

                }
            }).start();

        }

    }

    private boolean callWebServiceUpdateNums(String nums, String out_storage_detail_Id, String fmnums, String fmmid) {
        boolean result = false;

        try {

            /****************** 调用webService ***********************/
            // 调用.net 的WebService.
            String nameSpace = "http://dyjapp.org/";
            String methodName = "UpdateNums";


            String url = "http://" + sPreferencces.getString(BaseConstants.IP, "") + ":"
                    + sPreferencces.getString(BaseConstants.PORT, "")
                    + "/StoreCutMidServivce.asmx";

            String soapAction = nameSpace + methodName;

            // 设置连接参数
            SoapObject request = new SoapObject(nameSpace, methodName);

            // 增加属性参数。 将相关的函数参数放入到过程中。
            // request.addProperty("keyword", keyWord);
            request.addProperty("nums", nums);
            request.addProperty("out_storage_detail_Id", out_storage_detail_Id);
            request.addProperty("fmnums", fmnums);
            request.addProperty("fmmid", fmmid);

            SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
                    SoapEnvelope.VER11);// soap协议版本必须用SoapEnvelope.VER11（Soap
            // V1.1）;

            // 注意：这个属性是对dotnetwebservice协议的支持,如果dotnet的webservice
            // 不指定rpc方式则用true否则要用false
            envelope.dotNet = true;

            // envelope.setOutputSoapObject(request);//设置请求参数
            envelope.bodyOut = request; // enveloper.bodyOut=request 与
            // envelope.setOutputSoapObject(request)
            // 效果相同。
            // step4 创建HttpTransportSE对象
            HttpTransportSE ht = new HttpTransportSE(url);
            // step5 调用WebService
            ht.call(soapAction, envelope); // 关键的一步，很多问题都在这一步调试时出现问题。要么是IIS有问题，要么是ksoap2相关参数没配置好。
            if (envelope.getResponse() != null) {
                SoapPrimitive response = (SoapPrimitive) envelope.getResponse();
                // if ("1".equals(response.toString())) {
                String t = response.toString();

                if (t.equals("1")) {
                    result = true;
                }

            }
            /****************** 调用webService结束 ***********************/

        } catch (Exception e) {
            LoadingDialogUtil.dismissDialog();

            SYSException = e.toString();
        }

        return result;
    }

    private List<FmMaterialDetailInfo> callWebServiceGetFmInfo(String id) {
        List<FmMaterialDetailInfo> result = null;

        try {

            /****************** 调用webService ***********************/
            // 调用.net 的WebService.
            String nameSpace = "http://dyjapp.org/";
            String methodName = "GetfmmaterialByOid";

            String url = "http://" + sPreferencces.getString(BaseConstants.IP, "") + ":"
                    + sPreferencces.getString(BaseConstants.PORT, "")
                    + "/StoreCutMidServivce.asmx";

            String soapAction = nameSpace + methodName;

            // 设置连接参数
            SoapObject request = new SoapObject(nameSpace, methodName);

            // 增加属性参数。 将相关的函数参数放入到过程中。
            // request.addProperty("keyword", keyWord);
            request.addProperty("out_storage_detail_Id", id);

            SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
                    SoapEnvelope.VER11);// soap协议版本必须用SoapEnvelope.VER11（Soap
            // V1.1）;

            // 注意：这个属性是对dotnetwebservice协议的支持,如果dotnet的webservice
            // 不指定rpc方式则用true否则要用false
            envelope.dotNet = true;

            // envelope.setOutputSoapObject(request);//设置请求参数
            envelope.bodyOut = request; // enveloper.bodyOut=request 与
            // envelope.setOutputSoapObject(request)
            // 效果相同。
            // step4 创建HttpTransportSE对象
            HttpTransportSE ht = new HttpTransportSE(url);
            // step5 调用WebService
            ht.call(soapAction, envelope); // 关键的一步，很多问题都在这一步调试时出现问题。要么是IIS有问题，要么是ksoap2相关参数没配置好。
            if (envelope.getResponse() != null) {
                SoapPrimitive response = (SoapPrimitive) envelope.getResponse();
                // if ("1".equals(response.toString())) {
                String t = response.toString();

                if (!t.equals("") && !t.equals("[]")) {
                    result = fmMaterialDetailInfo.getListFromJSON(t);
                }

            }
            /****************** 调用webService结束 ***********************/

        } catch (Exception e) {
            LoadingDialogUtil.dismissDialog();

            SYSException = e.toString();
        }

        return result;
    }

    // 绑定信息
    private void bindInfo() {

        List<String> li_fminfo = new ArrayList<String>();
        if (li_fm.size() > 0) {
//            li_fminfo.add("111" + "|" +"222");
//            li_fminfo.add("333" + "|" +"444");
//            li_fminfo.add("555" + "|" +"666");

            for (FmMaterialDetailInfo p : li_fm) {
                li_fminfo.add(p.getMaterial() + "_" + p.getFmmid());
            }
        }

        projectAda = new MyAutoAarryAdapter(StoreSGJLEditMaterialNums.this,
                R.layout.store_adapter_mylist_item, li_fminfo);
        s_qrc_fmmaterial.setAdapter(projectAda);
    }

}